import requests
from lxml import etree
import os

class myPlay(object):

    def getHtml(self):
        print("进入视频获取方法")
        url = "https://ibaotu.com/shipin/"

        headers = {
            'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36 Edg/97.0.1072.55'
        }
        rep = requests.get(url, headers=headers)
        #print(rep.text)
        domTree = etree.HTML(rep.text)
        #print("将界面全部信息放入lxml解析器中，解析信息是：")
        #print(domTree)
        res = domTree.xpath('//li')[5]
        #print(res)

        #获取视频的名称和所在地址
        nameList = res.xpath('(//span[@class="video-title"]/text())')
        srcList = res.xpath('(//div[@class="video-play"]/video/@src)')
        #print(nameList)
        #print(srcList)
        for name, src in zip(nameList, srcList):
            print("视频标题："+name+",访问地址："+src)
            self.downMP4(name, src)
    #下载mp4视频
    def downMP4(self, name, src):
        print("进入视频下载方法")
        mp4Path = "d:/homework/实训/大三上/MP4/"+name+".mp4"

        try:
            #断点续抓
            if not os.path.exists("d:/homework/实训/大三上/MP4/"):
                os.mkdir("d:/homework/实训/大三上/MP4/")
            if not os.path.exists(mp4Path):
                content=requests.get("http:"+src).content
                with open(mp4Path, "wb") as f:
                    f.write(content)
                    f.close()
                    print("抓取视频成功")
        except Exception as e:
            print("抓取视频失败，原因是："+e.args)